package com.test2015.ui.button.hyperlink;

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import javax.swing.JButton;

public class HyperLink extends JButton{
	private HyperLink thisLink = this;
	private URL url = null;
	private boolean useUnderLine = false;

	public HyperLink(URL url){
		this.url = url;
		
	     setBorderPainted(false);
	     setContentAreaFilled(false);
	     this.setText(url.toString());
	     this.setToolTipText(url.toString());
	     
		setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		setMargin(new Insets(0, 0, 0, 0));
		
		this.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent actionevent) {
	            Desktop desktop = Desktop.getDesktop();
	            try {
					desktop.browse(url.toURI());
				} catch (Exception e) {
					e.printStackTrace();
				}			
			}
		});
		
		
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent mouseevent) {
				useUnderLine = true;
				thisLink.repaint();
			}
			
			@Override
			public void mouseExited(MouseEvent mouseevent) {
				useUnderLine = false;
				thisLink.repaint();
			}
		});
	}
	
	@Override
	protected void paintComponent(Graphics g) {
//		super.paintComponent(g);
		String urlStr = url.toString();
		Graphics2D g2d = (Graphics2D)g;
		
//		Font font = new Font(Font.DIALOG, Font.PLAIN, 12);
//		g2d.setFont(font);
		
		int x = 1;
		int y = 10;
		g2d.drawString(urlStr, x, y);
		if(useUnderLine){
			
			FontMetrics fontMetrics = g.getFontMetrics();
			Rectangle2D str = fontMetrics.getStringBounds(urlStr, g2d);
			
			int width2 = (int) str.getWidth();
			int height2 = (int) str.getHeight()-3;
			
			g2d.drawLine(x, height2, x+width2,height2);
			
		}
		
		
	}
	
}

